'use strict';
const {
	pageFundBaseList
} = require('lg-request-fund');
const {
	confMap
} = require("lg-constant");
const {
	parser,
	success,
	exception,
	error,
	typeOf,
	getTimingLogger
} = require("lg-utils");
const db = uniCloud.database();
const dbCmd = db.command;
const fundColl = db.collection("fund-base");
const logTimingColl = db.collection("log-timing");
// 更新基金基本信息
exports.main = async (event, context) => {
	try {
		const pageSize = 100;
		let updateCount = 0;
		const count = await this.fetchFundListTotal();
		if (count) {
			const countInt = Number.parseInt(count);
			const pageCount = Math.ceil(countInt / pageSize);
			for (let i = 1; i <= pageCount; i++) {
				try {
					const {
						data: {
							result: {
								data: {
									data: list = []
								} = {}
							} = {},
						} = {},
						status = ""
					} = await pageFundBaseList({
						page: i,
						num: pageSize
					}) || {};
					if (confMap.get("success") === status) {
						if (list && list.length) {
							const promises = [];
							for (let [listIndex, listValue] of Object.entries(list)) {
								const {
									symbol = ""
								} = listValue || {};
								promises.push(fundColl.where({
									symbol
								}).update(listValue));
							}
							try {

								const execPromiseAllResults = await Promise.all(promises) || [];
								const partUpdateList = execPromiseAllResults.filter(({
									affectedDocs,
									updated
								} = {}) => {
									return updated === 1
								})
								if (partUpdateList && partUpdateList.length) {
									const partUpdateCount = partUpdateList.length || 0;
									updateCount += partUpdateCount;
								}
							} catch (e) {

								logTimingColl.add(getTimingLogger({
									action: "updateFundBase",
									info: `更新数据请求异常;异常页数:${i}`,
									type: confMap.get("timing-error"),
									exceptionData: e
								}));
								continue;
							}
						}
					} else {

						logTimingColl.add(getTimingLogger({
							action: "updateFundBase",
							info: "请求远程分页数据异常;",
							type: confMap.get("timing-error"),
							exceptionData: {
								index: i,
								err: status
							}
						}));
						continue;
					}

				} catch (e) {

					logTimingColl.add(getTimingLogger({
						action: "updateFundBase",
						info: "循环更新捕获数据列表异常;",
						type: confMap.get("timing-error"),
						exceptionData: e
					}))

				}
			}

			logTimingColl.add(getTimingLogger({
				action: "updateFundBase",
				info: `更新数据项:${updateCount};`,
			}))
		} else {
			logTimingColl.add(getTimingLogger({
				action: "updateFundBase",
				info: "捕获基金基础信息列表总条目数异常;",
				type: confMap.get("timing-error"),
				exceptionData: count
			}))
		}
	} catch (e) {
		logTimingColl.add(getTimingLogger({
			action: "updateFundBase",
			info: "更新基金基础信息异常;",
			type: confMap.get("timing-exception"),
			exceptionData: e
		}))
	}
};
